import React,{ Component } from 'react'
import './DiskNode.css'
import { Tooltip } from 'antd'
import { cd_dir,download } from '../../actions/disk'
import { connect } from 'react-redux'

class DiskNode extends Component {
  defaultNode = 'defaultNode'
  defaultIcon = 'defaultIcon'
  onmouseoverNode = 'onmouseoverNode'
  onmouseoverIcon = 'onmouseoverIcon'

  constructor(props){
    super(props)
    this.stack = this.props.stack
    this.state = {
      NodeStyle:this.defaultNode,
      IconStyle:this.defaultIcon,
      selection:false
    }
    this.type = extlist[this.props.type]
    if (typeof(this.type) === 'undefined') this.type = 'file'
  }

  handleonClick = () => {
    this.setState({
      selection: !this.state.selection
    })
    let index
    if (!this.state.selection) {
      if (this.props.type === 'folder') {
        index = this.props.stack.dirs.indexOf(this.props.id)
        if (index === -1) {
          this.props.stack.dirs.push(this.props.id)
        }
      }else {
        index = this.props.stack.files.indexOf(this.props.id)
        if (index === -1) {
          this.props.stack.files.push(this.props.id)
        }
      }
    }else{
      if (this.props.type === 'folder') {
        index = this.props.stack.dirs.indexOf(this.props.id)
        if (index !== -1) this.props.stack.dirs.splice(index,1)
      }else {
        index = this.props.stack.files.indexOf(this.props.id)
        if (index !== -1) this.props.stack.files.splice(index,1)
      }
    }
    this.props.Refresh()
  }

  handleonDoubleClick = () => {
    const { dispatch } = this.props
    if (this.props.type === 'folder') {
      dispatch(cd_dir(dispatch,this.props.id))
    }else {
      dispatch(download(dispatch,this.props.id))
    }
  }

  handleonMouseOver = () => {
    this.setState({
      NodeStyle:this.onmouseoverNode,
      IconStyle:this.onmouseoverIcon
    })
  }

  handleonMouseOut = () => {
    this.setState({
        NodeStyle:this.defaultNode,
        IconStyle:this.defaultIcon
    })
  }

  render() {
    return (
      <Tooltip placement="bottomRight" title={this.props.name}>
      <div className={this.state.NodeStyle}
        onMouseOver={this.handleonMouseOver}
        onMouseOut={this.handleonMouseOut}
        onClick={this.handleonClick}
        onDoubleClick={this.handleonDoubleClick}
        >
        <div className={this.state.IconStyle}>
            <span className={"MyIcon iconfont icon-"+this.type}></span>
            <span className={this.state.selection?'MyIcon iconfont icon-fangxingxuanzhong':''}></span>
        </div>
        <p className='MyP'>{this.props.name}</p>
      </div>
      </Tooltip>
    )
  }
}

const extlist = {
  'folder':'folder',
  'application/oct' : 'execl',
  'application/pdf' : 'pdf',
  'application/vnd' : 'ppt',
  'audio/mp3' : 'mp3',
  'image/jpeg' : 'jpg',
  'image/png' : 'png',
  'text/html': 'html',
  'application/zip':'zip',
  'text/plain':'txt'
}

export default connect()(DiskNode)
